<template>

  <div :style="{height:height+30+'px',width:width}">
    <el-button v-if="!loading" type="success" icon="el-icon-download" size="mini"
      @click="getChartImage">导出报告</el-button>
    <div class="chart" ref="chart" :style="{height:height+'px',width:width}"></div>
  </div>
</template>

<script>
  import * as echarts from 'echarts'
  require('echarts/theme/macarons') // echarts theme
  import resize from './mixins/resize'

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: Number,
        default: window.innerHeight - 100, // 初始高度，可以根据需要调整
      },
      text: {
        type: String,
        default: ''
      },
      subtext: {
        type: String,
        default: ''
      },
      unit: {
        type: Number,
        default: 1024,
      },
      chartData: {
        type: Object,
        required: true
      }
    },
    watch: {
      unit: {
        deep: true,
        handler(val) {
          this.unitShow = val
          this.setOptions(this.chartData)
        }
      },
      chartData: {
        deep: true,
        handler(val) {
          this.setOptions(val)
        }
      },
      subtext: {
        deep: true,
        handler(val) {
          this.subtext = val;
        }
      },
      text: {
        deep: true,
        handler(val) {
          this.text = val;
        }
      }
    },
    data() {
      return {
        loading: false,
        chart: null,
        dataURL: "",
        unitShow: this.unit
      }
    },
    mounted() {
      this.chart = echarts.init(this.$refs.chart, 'macarons')
      this.$nextTick(() => {
        this.setOptions(this.chartData)
      })
    },
    created() {

    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      getChartImage() {
        this.loading = true;
        // 使用 toDataURL 方法将 canvas 内容转换为图片数据
        this.dataURL = this.chart.getDataURL({
          type: 'png',
          pixelRatio: 2, // 将像素比例设置为 2，即默认大小的两倍
        });
        this.$emit('handleSetSetChartImage', this.dataURL);

        console.log(this.dataURL)
        // 返回 base64 图片数据
        this.loading = false;
      },


      setOptions({
        expectedData,
        actualData
      } = {}) {
        let unSelectedLegend = {};
        // 判断 expectedData 的长度
        if (expectedData.length > 10) {
          // 只取第11条到最后的所有条目
          const slicedData = expectedData.slice(10);
          // 将数组转换为对象
          unSelectedLegend = slicedData.reduce((accumulator, currentPath) => {
            accumulator[currentPath] = false;
            return accumulator;
          }, {});

        }

        // 移除之前的点击事件监听器
        if (this.chart) {
          this.chart.off('dblclick');
        }
        this.chart.setOption({
          title: {
            text: this.text,
            subtext: this.subtext,
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c}' + (this.unitShow == 1 ? 'B' : this.unitShow == 1024 ? 'KB' : this
              .unitShow == 1024 * 1024 ? 'MB' : this.unitShow == 1024 * 1024 * 1024 ? 'GB' : '个') + ' ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'right',
            type: 'scroll',
            selected: unSelectedLegend
          },
          toolbox: {
            show: true,
            left: 'left',
            feature: {
              // mark: {
              //   show: true
              // },
              // dataView: {
              //   show: true,
              //   readOnly: false
              // },
              // restore: {
              //   show: true
              // },
              // saveAsImage: {
              //   show: true
              // }
            }
          },
          series: [{
            name: '占上一层%',
            label: {
              show: true,
              position: 'outside',

              formatter: '{b}: {c} ' + (this.unitShow == 1 ? 'B' : this.unitShow == 1024 ? 'KB' : this
                .unitShow == 1024 * 1024 ? 'MB' : this.unitShow == 1024 * 1024 * 1024 ? 'GB' : '个') + '({d}%)'
            },
            type: 'pie',
            // roseType: 'area',
            radius: [0, 280],
            itemStyle: {
              borderRadius: 8
            },
            center: ['50%', '50%'],
            data: actualData,
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }]
        });

        // 绑定点击事件
        this.chart.on('dblclick', (params) => {
          console.log('点击了数据点：', params);
          // 在这里根据 params 进行相应的处理
          this.handleClick(params);
        });
      },

      handleClick(params) {

         this.$emit('dblClickEventCharts', params);
        // 处理点击事件
       // alert(`您点击了 ${params.name}，销量：${params.value}`);
      }

    }
  }
</script>
